import threading
import time

import serial

from pymodbus.client import serial


class UartConnector:
    _instance = None
    _instance_lock = threading.Lock()

    @classmethod
    def get_instance(cls):
        if not cls._instance:
            with cls._instance_lock:
                if not cls._instance:
                    cls._instance = UartConnector()
        return cls._instance

    def __init__(self):
        # self.uart = serial.Serial('/dev/ttyUSB0', 9600)
        self.uart_client = None

    def uart_client(self, port: str, baud_rate: int = 9600, byte_size: int = 8, parity: str = "N", stop_bits: int = 1,
                    timeout=3):
        if self.uart_client is None:
            try:
                self.uart_client = serial.Serial(port, baud_rate, byte_size, parity, stop_bits, timeout)
                # config enable rs485 model
                self.uart_client.rts = False
                self.uart_client.dtr = False
            except serial.SerialException as e:
                print(f"uart client exception: {e}")
        else:
            print(f"uart client is already connected: {self.uart_client}")

    def uart_write(self, data: bytes):
        """
        uart write function
        :param data:
        :return:
        """
        self.uart_client.write(data)
        time.sleep(0.1)
        # 接收数据
        received_data = self.uart_client.readline()
        print(f"uart client received data: {received_data}")

    def uart_read(self):
        self.uart_client.readinto()
        pass
